// packageCustomer/pages/addVisitCustomerRecord/addVisitCustomerRecord.js

const {
  deepClone,
  padStart,
  type,
  deepMerge,
  alert
} = require("../../../js/newUtil")

import {
  customer
} from '../../../js/modules/customer'
import {
  api,
} from '../../../js/util'

const app = getApp()
const pageBehavior = require('../../../js/common/PageBehavior')

let locked = false


let forms = [{
    type: 'select',
    name: '拜访客户',
    placeholder: '请选择客户',
    key: 'customer',
    value: '',
    action: 'toPage',
    url: 'packageCustomer/pages/chooseCustomer/index?formKey=customer&multiple=false&style=2'
  },
  {
    type: 'input',
    name: '拜访时间',
    placeholder: '获取当前时间',
    value: '',
    disabled: true,
    key: 'date',
  },
  {
    type: 'location',
    name: '拜访地址',
    value: {},
    key: 'address',
  },
  {
    type: 'textarea',
    name: '拜访内容',
    placeholder: '拜访信息',
    value: '',
    showLimit: true,
    maxLength: 2000,
    key: 'content',
    required: true,
    valid: {
      required: '请填写拜访内容'
    }
  },
  {
    type: 'img',
    name: '拜访拍照',
    value: [],
    showLimit: true,
    maxLength: 9,
    key: 'img',
    required: true,
    sourceType: ['camera'],
    valid: {
      required: '请添加拜访拍照'
    }
  }
]

Page({
  behaviors: [pageBehavior],
  
  pageKey: 'addVisitCustomer',

  /**
   * 页面的初始数据
   */
  data: {
    isIphoneX: app.globalData.isIphoneX,
    mainColor: api.titleColor || "#e56b14",
    forms: [],
    webViewSrc: '',
    fontSizeScale: 1,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    let addForm = deepClone(forms)
    // 如果传入客户信息，则将其设为当前默认
    if (options.customerId) {
      let customer = options.customer || ''
      customer = decodeURIComponent(customer)
      addForm[0].showValue = customer
      addForm[0].value = [{
        Id: options.customerId || '',
        ShopName: customer
      }]
    }
    let now = this.getNow()
    addForm[1].value = now
    // 如果传入地址信息，则使用传入的，不再去自动获取
    if (options.latitude) {
      let address = decodeURIComponent(options.address || '')
      let province = decodeURIComponent(options.province || '')
      let city = decodeURIComponent(options.city || '')
      let district = decodeURIComponent(options.district || options.area || '')
      addForm[2].value = {
        latitude: options.latitude,
        longitude: options.longitude,
        address: address,
        province: province,
        city: city,
        district: district
      }
      addForm[2].showValue = address
      addForm[2].getLocation = true
    }
    // 返回上个webview页面需要刷新的页面地址
    let src = options.src || options.webViewSrc || ''
    src = decodeURIComponent(src)
    this.setData({
      forms: addForm,
      webViewSrc: src
    })
    // 字体缩放
    let fontSizeScale = app.globalData.fontSizeScale || 1
    this.setData({
      fontSizeScale
    })
  },

  getNow() {
    let now = new Date()
    let year = now.getFullYear()
    let month = padStart(now.getMonth() + 1, 2, '0')
    let date = padStart(now.getDate(), 2, '0')
    let hour = padStart(now.getHours(), 2, '0')
    let min = padStart(now.getMinutes(), 2, '0')
    let sec = padStart(now.getSeconds(), 2, '0')
    return `${year}年${month}月${date}日 ${hour}:${min}:${sec}`
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },


  pageMethod(e) {
    let methodName = e.detail.methodName
    if (this[methodName]) {
      this[methodName]()
    }
  },

  selected(e) {
    console.log(e)
    let component = this.selectComponent('#form')
    let form = component.data.form
    let id = this.data.id
    let contact = this.data.contact
    if (e.formKey == 'customer' && e.data) {
      let index = form.findIndex((item) => {
        return item.range == 'contactList'
      })
      if (e.data[0].Id != id) {
        if (index != -1) {
          let contactList = form.splice(index, 1)
          contact = contactList[0]
        }
      } else {
        form.splice(1, 0, contact)
      }
    }
    for (let i = 0; i < form.length; i++) {
      if (e.formKey == form[i].key) {
        form[i].value = e.data
        if (type.isObject(form[i].value)) {
          form[i].showValue = form[i].value.ShopName || form[i].value.Name || form[i].value.value
        } else if (type.isArray(form[i].value)) {
          form[i].showValue = form[i].value.map((item) => {
            return item.ShopName || item.Name || item.value
          })
          if (form[i].showValue.length > 3) {
            form[i].showValue = form[i].showValue.splice(0, 3)
            form[i].showValue = form[i].showValue.join(',') + '...'
          } else {
            form[i].showValue = form[i].showValue.join(',')
          }
        }
        break
      }
    }
    // 将form赋值进当前页面forms,便于打开选择页面获取到默认值
    this.setData({
      contact,
      forms: form
    })
  },

  checkData: async function () {
    let form = this.selectComponent('#form')
    let valid = form.valid()
    if (!valid) {
      return
    }
    let obj = await form.getForm()
    let address = obj.address || {}
    obj = deepMerge(obj, address)

    if (locked) {
      return
    }
    locked = true
    this.submit(obj)
  },

  submit(data = {}) {
    customer.addCustomerVisit(data).then((res) => {
      console.log(res)
      if (!res.Success) {
        alert({
          content: res.Message || '提交失败，请稍后重试'
        })
        return
      }
      this.submitCompleted()
    }).catch((err) => {
      console.log(err)
    })
  },

  /**
   * 重设上个页面webview的src，用于刷新数据
   * 
   * 然后返回上个页面
   */
  submitCompleted() {
    let pages = getCurrentPages()
    let prevPage = pages[pages.length - 2]
    let src = (this.data.webViewSrc || prevPage.data.thirdPath)+'&time='+new Date().getTime()
    wx.navigateBack()
    setTimeout(() => {
      console.log(src)
      prevPage.setData({
        src: src,
        thirdPath: src
      })
    }, 1000)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    locked = false
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})